﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using giaoxuhaison.Models;
using System.Web.Mvc;
using System.Web.Security;
using DotNetOpenAuth.AspNet;
using Microsoft.Web.WebPages.OAuth;
using WebMatrix.WebData;
using giaoxuhaison.Common;
using giaoxuhaison.MembershipServices;
using System.Data.Entity;
using System.Data;
using System.IO;
using System.Web.Helpers;


namespace giaoxuhaison.Controllers
{
    public class AdminController : Controller
    {
        //
        // GET: /Admin/
        private IBuildGridDataHelper<LabelModels> _gridhelper;
        private IBuildGridDataHelper<LabelModels> _gridhelperBookAll;
        private IBuildGridDataHelper<ManageUserModels> _gridhelperUser;
        private IBuildGridDataHelper<ManageUserModels> _gridhelperUserAll;  
        private gxhaisonEntities conn = new gxhaisonEntities();
        private bool Initialized = false;

        public ActionResult _FooterAdmin()
        {
            return View();
        }

        public ActionResult Index(string returnUrl)
        {
            return View();
        }

        public ActionResult ManageGodtitlePanel()
        {
            if (Request.IsAuthenticated)
            { 
                return View();
            }
            else
            {
                return RedirectToAction("Index", "Admin"); ;
            }            
        }

        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public ActionResult Index(UserModels model, string returnUrl)
        {
            //xu ly phan login
            if (ModelState.IsValid)
            {
                string strError = ValidateUser(model);
                if (!string.IsNullOrEmpty(strError))
                {
                    ModelState.AddModelError("", strError);
                    return View(model);
                }

                //login system
                strError = LoginSystem(model);
                if (!string.IsNullOrEmpty(strError))
                {
                    ModelState.AddModelError("", strError);
                    return View(model);
                }

                return RedirectToLocal(returnUrl);
            }

            // If we got this far, something failed, redisplay form
            ModelState.AddModelError("", "User không có quyền đăng nhập, vui lòng liên hệ quản trị hệ thống!");
            return View(model);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult LogOff()
        {
            //WebSecurity.Logout();
            FormsAuthentication.SignOut();
            System.Web.HttpContext.Current.Session.Remove(AuthConfig.UserInfo.UserName);
            return RedirectToAction("Index", "Admin");
        }

        private string ValidateUser(UserModels user)
        {
            if (string.IsNullOrEmpty(user.UserName))
                return "Vui lòng nhập tên đăng nhập!";
            if (string.IsNullOrEmpty(user.Password))
                return "Vui lòng nhập mật khẩu!";

            return string.Empty;
        }

        private string LoginSystem(UserModels model)
        {
            try
            {
                //xu ly login
                var Login = conn.Users.Where(t => t.Locked == false && t.UserName == model.UserName).ToList();

                if (Login.Count() == 0)
                {
                    return "User không tồn tại hoặc bị khóa!";
                }

                AuthConfig.UserInfo = Login[0] as User;

                System.Web.HttpContext.Current.Session.Remove(AuthConfig.UserInfo.UserName);
                System.Web.HttpContext.Current.Session.Add(AuthConfig.UserInfo.UserName, AuthConfig.UserInfo);

                FormsAuthentication.SetAuthCookie(AuthConfig.UserInfo.DisplayName, false);
            }
            catch (Exception ex)
            {
                return ex.Message;
            }

            return string.Empty;
        }
        private ActionResult RedirectToLocal(string returnUrl)
        {
            if (Url.IsLocalUrl(returnUrl))
            {
                return Redirect(returnUrl);
            }
            else
            {
                return RedirectToAction("Index", "Admin");
            }
        }

        private string[] CreateRowsJSonLabelAll(LabelModels model)
        {
            List<string> result = new List<string>();
            string format = "dd-mm-yyyy";
            result.Add(model.LabelID.ToString());
            result.Add(model.Subject);
            result.Add(model.Author);
            result.Add(model.Contents);
            result.Add(model.CreationDate.ToShortDateString());            
            return result.ToArray();
        }

        private void InitHelperLabelAll()
        {
            /*
             * Hungnvv : 03/04/2013
             */

            IEntityHelper entity = new EntityHelper();
            IPageCalculator pageCalc = new PageCalculator();
            ISortBuilder _sortBuilder = new SortBuilder(entity);
            IFilterBuilder _filterBuilder = new FilterBuilder(entity);

            //this._retrieveHandler = new RetrieveHandler(entity);
            this._gridhelperBookAll = new BuildGridDataHelper<LabelModels>(pageCalc, entity, _sortBuilder, _filterBuilder);

            Initialized = true;

            return;
        }
        public string GetAllLabels(string Condition_Subject, string Condition_Author, string Condition_Contents, string sortName, string sortOrder, int rowNumber, int rowId,
            int page, string searchField, string searchOper, string searchString)
        {
            if (!Initialized) InitHelperLabelAll();

            LabelModels model = new LabelModels();
            model.Condition_Subject = Condition_Subject;
            model.Condition_Author = Condition_Author;
            model.Condition_Contents = Condition_Contents;

            return _gridhelperBookAll.BuildDataForGrid(GetListAllLabels(model), CreateRowsJSonLabelAll,
              sortName, "desc", rowNumber, rowId, page, searchField, searchOper, searchString);

        }

        private List<LabelModels> GetListAllLabels(LabelModels modelNewsAll)
        {

            var Item = conn.LabelAlls.Where(t => t.Subject.Contains(modelNewsAll.Condition_Subject) && t.Author.Contains(modelNewsAll.Condition_Author) && t.Contents.Contains(modelNewsAll.Condition_Contents)).OrderByDescending(t => t.CreationDate).ToList();
            
            List<LabelModels> lst = new  List<LabelModels>();

            foreach (var t in Item)
            {
                LabelModels model = new LabelModels();
                model.Condition_Subject = t.Subject;
                model.Condition_Author = t.Author;
                model.Condition_Contents = t.Contents;
                model.LabelID = t.LabelID;
                model.Subject = t.Subject;
                model.Author = t.Author;
                model.Contents = t.Contents;
                model.CreationDate = t.CreationDate;
                lst.Add(model);
            }

            return lst;
        }

        [HttpPost]
        public ActionResult ManageGodtitlePanel(LabelModels model)
        {
            //if (ModelState.IsValid)
            if (ValidateLabel(model))
            {
                LabelAll Item = new LabelAll();
                Item.LabelID = model.LabelID;
                Item.Subject = model.Subject;
                Item.Author = model.Author;
                Item.Contents = model.Contents;
                Item.Locked = model.Locked;
                Item.CreationBy = AuthConfig.UserInfo.UserID;
                Item.CreationDate = model.CreationDate;
                Item.LastUpdatedBy = AuthConfig.UserInfo.UserID;
                Item.LastUpdatedDate = DateTime.Now;

                try
                {
                    if (model.LabelID == null || model.LabelID.ToString() == "" || model.LabelID == 0)//insert
                    {
                        conn.LabelAlls.AddObject(Item);                    
                        conn.SaveChanges();
                        ModelState.AddModelError("", "Thêm mới thành công!");                   
                    }
                    else //update
                    {
                       
                        conn.LabelAlls.Attach(Item);
                        conn.ObjectStateManager.ChangeObjectState(Item, EntityState.Modified);
                        conn.SaveChanges();
                        ModelState.AddModelError("", "Cập nhật thành công!");                   
                    }
                }
                catch
                {
                    ModelState.AddModelError("", ValidateMessages.ErrorDescription(MembershipStatus.Error));
                }
            }

            return View(model);
        }
        private bool ValidateLabel(LabelModels model)
        {
            if(model.Subject == null || model.Subject.ToString() == "")
            {
                ModelState.AddModelError("", "Xin vui lòng nhập tiêu đề!");                   
                return false;
            }
            if (model.Author == null || model.Author.ToString() == "")
            {
                ModelState.AddModelError("", "Xin vui lòng nhập câu Lời Chúa!");
                return false;
            }
            if (model.Contents == null || model.Contents.ToString() == "")
            {
                ModelState.AddModelError("", "Xin vui lòng nhập câu lời cầu nguyện!");
                return false;
            }
            if (model.CreationDate == null || model.CreationDate.ToString() == "")
            {
                ModelState.AddModelError("", "Xin vui lòng nhập ngày!");
                return false;
            }
            return true;
        }
        public ActionResult DeleteLabel(string LabelID)
        {
            if (LabelID.ToString() != "" && LabelID != "0")
            {
                LabelAll model = new LabelAll();
                int strLabelID = int.Parse(LabelID);

                model = (LabelAll)conn.LabelAlls.Where(t => t.LabelID == strLabelID).SingleOrDefault();

                try
                {
                    conn.LabelAlls.DeleteObject(model);
                    conn.SaveChanges();
                    ModelState.AddModelError("", "Xóa dữ liệu thành công!");                   
                    return Json("Xóa dữ liệu thành công", JsonRequestBehavior.AllowGet);
                }
                catch (Exception ex)
                {

                    return Json("Xóa dữ liệu lỗi, vui lòng liên hệ quản trị hệ thống!", JsonRequestBehavior.AllowGet);
                }
            }
            //return RedirectToAction("DeleteNewsCatalogueSuccess");
            return Json(string.Empty, JsonRequestBehavior.AllowGet);
        }

        public ActionResult ChangePass()
        {
            if (Request.IsAuthenticated)
            {
                return View();
            }
            else
            {
                return RedirectToAction("Index", "Admin"); ;
            }
        }

        [HttpPost]
        public ActionResult ChangePass(ChangePassModel model)
        {
            //if (ModelState.IsValid)
            if (ValidateChangePass(model))
            {
                User Item = new User();

                Item.UserID = AuthConfig.UserInfo.UserID;
                Item.RoleID = AuthConfig.UserInfo.RoleID;
                Item.UserName = AuthConfig.UserInfo.UserName;
                Item.UserPass = model.NewPassword;
                Item.DisplayName = AuthConfig.UserInfo.DisplayName;
                Item.Email = AuthConfig.UserInfo.Email;
                Item.IsChangePass = AuthConfig.UserInfo.IsChangePass;
                Item.IsActive = AuthConfig.UserInfo.IsActive;
                Item.LastAccessDate = DateTime.Now;
                Item.Locked = AuthConfig.UserInfo.Locked;
                Item.CreationBy = AuthConfig.UserInfo.UserID;
                Item.CreationDate = AuthConfig.UserInfo.CreationDate;
                Item.LastUpdatedBy = AuthConfig.UserInfo.LastUpdatedBy;
                Item.LastUpdatedDate = DateTime.Now;


                try
                {
                    conn.Users.Attach(Item);
                    conn.ObjectStateManager.ChangeObjectState(Item, EntityState.Modified);
                    conn.SaveChanges();
                    ModelState.AddModelError("", "Cập nhật thành công!");
                    AuthConfig.UserInfo.UserPass = Item.UserPass;
                }
                catch
                {
                    ModelState.AddModelError("", ValidateMessages.ErrorDescription(MembershipStatus.Error));
                }
            }

            return View(model);
        }
        private bool ValidateChangePass(ChangePassModel model)
        {
            //var usr = conn.Users.Where(t => t.UserID == AuthConfig.UserInfo.UserID).SingleOrDefault();

            if (model.OldPassword == null || model.OldPassword.ToString() == "")
            {
                ModelState.AddModelError("", "Xin vui lòng nhập mật khẩu cũ!");
                return false;
            }
            if (model.OldPassword != AuthConfig.UserInfo.UserPass)
            {
                ModelState.AddModelError("", "Mật khẩu cũ không đúng!");
                return false;
            }
            if (model.NewPassword == null || model.NewPassword.ToString() == "")
            {
                ModelState.AddModelError("", "Xin vui lòng nhập mật khẩu mới!");
                return false;
            }
            if (model.ConfirmPassword == null || model.ConfirmPassword.ToString() == "")
            {
                ModelState.AddModelError("", "Xin vui lòng nhập nhập xác nhận mật khẩu mới!");
                return false;
            }
            if (model.NewPassword != model.ConfirmPassword)
            {
                ModelState.AddModelError("", "Mật khẩu mới và xác nhận không khớp, xin vui lòng kiểm tra lại!");
                return false;
            }
            return true;
        }

        //upload file
        public ActionResult UploadFiles()
        {
            if (Request.IsAuthenticated)
            {
                return View("UploadFiles");
            }
            else
            {
                return RedirectToAction("Index", "Admin"); ;
            }
        }

        [HttpPost]
        public ActionResult UploadFile(UploadFileModel model, IEnumerable<UploadFileModel> files)
        {
            if (ModelState.IsValid)
            {
                if (Request.Files.Count < 1)
                {
                    ModelState.AddModelError("", "Bạn chưa chọn file hình cần tải lên.");
                    return View("UploadFiles", model);
                }

                var file = Request.Files[0];
                foreach (var intTag in Request.Files)
                {
                    //HttpPostedFileBase test = Request.Files[intTag];
                }

                List<string> lstFiles = new List<string>();
                string filename = model.FileName; //+Path.GetExtension(Path.GetFileName(file.FileName));
                int startPos = 1;
                //tach group file thanh nhieu file
                filename = filename.Replace("C:\\fakepath\\", "");
                string[] str = filename.Split('|');
                
                string filefullpath;

                try
                {
                    foreach (string strname in str)
                    {
                        if(strname != "" && strname != null)
                        {
                            var fileImg = strname.Remove(strname.IndexOf("."), strname.Length - strname.IndexOf(".")) + Path.GetExtension(Path.GetFileName(file.FileName));
                            
                            if (model.Folder != "" && model.Folder != null)
                            {
                                var folder = Server.MapPath(Url.Content(model.SavePath) + model.Folder);
                                Directory.CreateDirectory(folder);
                                filefullpath = Path.Combine(Request.MapPath(Url.Content(model.SavePath)+ model.Folder + "/"), fileImg);
                                file.SaveAs(filefullpath);
                            }
                            else
                            {
                                filefullpath = Path.Combine(Request.MapPath(Url.Content(model.SavePath)), fileImg);
                                file.SaveAs(filefullpath);
                            }
                        }
                    }
                    ModelState.AddModelError("", "Tải hình lên thành công !");
                }
                catch
                {
                    ModelState.AddModelError("", "Có lỗi trong quá trình tải hình lên. Vui lòng thử lại sau.");
                }
            }
            return View("UploadFiles", model);
        }

        public ActionResult UploadMultiFiles()
        {
            if (Request.IsAuthenticated)
            {
                return View();
            }
            else
            {
                return RedirectToAction("Index", "Admin"); ;
            }
        }

        [HttpPost]
        public ActionResult UploadMultiFiles(UploadFileModel model)
        {
            if (ModelState.IsValid)
            {
                if (Request.Files.Count < 1)
                {
                    ModelState.AddModelError("", "Bạn chưa chọn file hình cần tải lên.");
                    return View("UploadMultiFiles", model);
                }

                try
                {
                    
                    for (int i =0 ; i < Request.Files.Count; i++)                        
                    {
                        HttpPostedFileBase file = Request.Files[i];

                        string strname = file.FileName;
                        
                        if (strname != "" && strname != null)
                        {
                            var fileImg = strname.Remove(strname.IndexOf("."), strname.Length - strname.IndexOf(".")) + Path.GetExtension(Path.GetFileName(file.FileName));
                            string filefullpath = Path.Combine(Request.MapPath(Url.Content(model.SavePath)), strname);

                            if (model.Folder != "" && model.Folder != null)
                            {
                                var folder = Server.MapPath(Url.Content(model.SavePath) + model.Folder);
                                Directory.CreateDirectory(folder);
                                filefullpath = Path.Combine(Request.MapPath(Url.Content(model.SavePath) + model.Folder + "/"), fileImg);
                                //resize if get large files
                                WebImage img = new WebImage(file.InputStream);
                                if (img.Width > 700)
                                    img.Resize(700, 700, true);
                                img.Save(filefullpath);  
                                //file.SaveAs(filefullpath);
                            }
                            else
                            {
                                filefullpath = Path.Combine(Request.MapPath(Url.Content(model.SavePath)), fileImg);
                                //file.SaveAs(filefullpath);
                                //resize if get large files
                                WebImage img = new WebImage(file.InputStream);
                                if (img.Width > 500)
                                    img.Resize(500, 500,true);
                                img.Save(filefullpath);                                
                            }
                        }
                    }
                    ModelState.AddModelError("", "Tải hình lên thành công !");
                }
                catch
                {
                    ModelState.AddModelError("", "Có lỗi trong quá trình tải hình lên. Vui lòng thử lại sau.");
                }
            }
            return View("UploadMultiFiles", model);
        }


        /*phan quan ly user*/

        public ActionResult ErrorFunction()
        {
            return View();
        }

        public ActionResult ManageUsers()
        {
            if (Request.IsAuthenticated)
            {
                if (AuthConfig.UserInfo.RoleID == 1)
                {
                    ViewData["lstNewsGrp"] = GetListNewsGrp();
                    return View();
                }
                else
                {
                    return View("ErrorFunction");
                }
            }
            else
            {
                return RedirectToAction("Index", "Admin"); ;
            }
        }
        private List<ListGroupModels> GetListNewsGrp()
        {
            List<ListGroupModels> lst = new List<ListGroupModels>();
            ListGroupModels item = new ListGroupModels();
            ListGroupModels item1 = new ListGroupModels();
            
            item.GroupID = 1;
            item.GroupName = "Quyền quản trị";
            lst.Add(item);

            item1.GroupID = 2;
            item1.GroupName = "Quyền user";
            lst.Add(item1);

            return lst;
        }
        private string[] CreateRowsJSonUserAll(ManageUserModels model)
        {
            List<string> result = new List<string>();
            string format = "dd-mm-yyyy";
            result.Add(model.UserID.ToString());
            result.Add(model.UserName);            
            result.Add(model.RoleID.ToString());
            result.Add(model.RoleName);
            result.Add(model.DisplayName);
            result.Add(model.Email);
            result.Add(model.UserPass);            
            result.Add(model.IsActive.ToString());
            result.Add(model.Locked.ToString());
            result.Add(model.CreationDate.ToShortDateString());
            return result.ToArray();

        }

        private void InitHelperUsersAll()
        {
            /*
             * Hungnvv : 03/04/2013
             */

            IEntityHelper entity = new EntityHelper();
            IPageCalculator pageCalc = new PageCalculator();
            ISortBuilder _sortBuilder = new SortBuilder(entity);
            IFilterBuilder _filterBuilder = new FilterBuilder(entity);

            //this._retrieveHandler = new RetrieveHandler(entity);
            this._gridhelperUserAll = new BuildGridDataHelper<ManageUserModels>(pageCalc, entity, _sortBuilder, _filterBuilder);

            Initialized = true;

            return;
        }

        public string GetAllUsers(string Condition_Find, string sortName, string sortOrder, int rowNumber, int rowId,
            int page, string searchField, string searchOper, string searchString)
        {
            if (!Initialized) InitHelperUsersAll();

            ManageUserModels model = new ManageUserModels();
            model.Condition_Find = Condition_Find;

            return _gridhelperUserAll.BuildDataForGrid(GetListUsers(model), CreateRowsJSonUserAll,
              sortName, "desc", rowNumber, rowId, page, searchField, searchOper, searchString);

        }

        private List<ManageUserModels> GetListUsers(ManageUserModels modelNewsAll)
        {
            var Item = new List<User>();

            Item = conn.Users.Where(t => (t.UserName.Contains(modelNewsAll.Condition_Find) || t.DisplayName.Contains(modelNewsAll.Condition_Find) )).OrderByDescending(t => t.CreationDate).ToList();

            List<ManageUserModels> lst = new List<ManageUserModels>();

            foreach (var t in Item)
            {
                ManageUserModels model = new ManageUserModels();

                model.Condition_Find = t.UserName;
                model.UserID = t.UserID;
                model.RoleID = t.RoleID;

                if (t.RoleID == 1)
                {
                    model.RoleName = "Quyền quản trị";
                }
                else
                {
                    model.RoleName = "Quyền User";
                }
                model.UserName = t.UserName;
                model.UserPass = t.UserPass;
                model.DisplayName = t.DisplayName;
                model.Email = t.Email;
                model.IsActive = t.IsActive;
                model.Locked = t.Locked;
                model.CreationDate = t.CreationDate;
                lst.Add(model);
            }

            return lst;
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult ManageUsers(ManageUserModels model)
        {
            //if (ModelState.IsValid)
            if (ValidateUser(model))
            {
                TimeSpan ts = new TimeSpan(DateTime.Now.Hour, DateTime.Now.Minute, DateTime.Now.Second);

                User Item = new User();

                Item.UserID = model.UserID;                    
                Item.RoleID = model.RoleID;                   
                Item.UserName = model.UserName;                   
                Item.UserPass = model.UserPass;                   
                Item.DisplayName = model.DisplayName;                   
                Item.Email = model.Email;                   
                Item.IsChangePass = false;                   
                Item.IsActive = model.IsActive;
                Item.LastAccessDate = DateTime.Now;                   
                Item.Locked = model.Locked;
                Item.CreationBy = AuthConfig.UserInfo.UserID;
                Item.CreationDate = model.CreationDate + ts;
                Item.LastUpdatedBy = AuthConfig.UserInfo.UserID;
                Item.LastUpdatedDate = DateTime.Now;

                try
                {
                    if (model.UserID == null || model.UserID.ToString() == "" || model.UserID == 0)//insert
                    {
                        conn.Users.AddObject(Item);
                        conn.SaveChanges();
                        ModelState.AddModelError("", "Thêm mới thành công!");
                    }
                    else //update
                    {

                        conn.Users.Attach(Item);
                        conn.ObjectStateManager.ChangeObjectState(Item, EntityState.Modified);
                        conn.SaveChanges();
                        ModelState.AddModelError("", "Cập nhật thành công!");
                    }
                }
                catch
                {
                    ModelState.AddModelError("", ValidateMessages.ErrorDescription(MembershipStatus.Error));
                }
            }

            ViewData["lstNewsGrp"] = GetListNewsGrp();
            return View(model);
        }

        private bool ValidateUser(ManageUserModels model)
        {
            if (model.UserName == null || model.UserName.ToString() == "")
            {
                ModelState.AddModelError("", "Xin vui lòng nhập tên đăng nhập!");
                return false;
            }
            if (model.UserPass == null || model.UserPass.ToString() == "")
            {
                ModelState.AddModelError("", "Xin vui lòng nhập mật khẩu mặc định!");
                return false;
            }
            if (model.DisplayName == null || model.DisplayName.ToString() == "")
            {
                ModelState.AddModelError("", "Xin vui lòng nhập tên đầy đủ!");
                return false;
            }
            if (model.Email == null || model.Email.ToString() == "")
            {
                ModelState.AddModelError("", "Xin vui lòng nhập thông tin email!");
                return false;
            }
            if (model.CreationDate == null || model.CreationDate.ToString() == "")
            {
                ModelState.AddModelError("", "Xin vui lòng nhập ngày!");
                return false;
            }
            return true;
        }
    }
    
}
